package com.dai.rpc.register.zookeeper;

import com.dai.rpc.config.MyRpcConfig;
import com.dai.rpc.constant.MyRpcConstants;
import com.dai.rpc.exceptions.MyRpcException;
import com.dai.rpc.factory.SingletonFactory;
import com.dai.rpc.loadbanlance.LoadBalance;
import com.dai.rpc.loadbanlance.loadbanlancer.RandomLoadBalance;
import com.dai.rpc.message.RpcRequest;
import com.dai.rpc.register.ServiceDiscovery;
import com.dai.rpc.util.CuratorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;

import java.net.InetSocketAddress;
import java.util.List;

@Slf4j
public class ZKServiceDiscovery implements ServiceDiscovery {

    private final LoadBalance loadBalance;
    private MyRpcConfig myRpcConfig;

    public ZKServiceDiscovery() {
        this.loadBalance = SingletonFactory.getInstance(RandomLoadBalance.class);
    }
    /**
     * 服务发现
     * @param rpcRequest
     * @return
     */
    @Override
    public InetSocketAddress lookupService(RpcRequest rpcRequest) {

        String interfaceName = rpcRequest.getInterfaceName();
        String version = rpcRequest.getVersion();
        String serviceName = myRpcConfig.getZKGroup() + interfaceName + version;
        // 获取 zookeeper 连接
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        List<String> childrenNodes = CuratorUtils.getChildrenNodes(zkClient, serviceName);
        if(childrenNodes == null || childrenNodes.size() == 0){
            throw new MyRpcException("未发现可用服务实例");
        }
        // 负载均衡挑选一个服务（管道） 10.243.77.144:13567、10.243.77.144:13568
        String server = loadBalance.selectServiceAddress(childrenNodes, rpcRequest);
        log.info("成功获取到服务地址：{}", server);
        String[] split = server.split(":");
        String host = split[0];
        int port = Integer.parseInt(split[1]);
        return new InetSocketAddress(host, port);
    }

    public void init(MyRpcConfig myRpcConfig){
        this.myRpcConfig = myRpcConfig;
    }
}
